package com.youhome.mobile.controller;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.JSMSClient;
import cn.jsms.api.ValidSMSResult;
import com.youhome.common.config.SMSConfig;
import com.youhome.common.exception.CustomException;
import com.youhome.common.response.Result;
import com.youhome.common.response.ResultCode;
import com.youhome.mobile.config.SMSAuthenticationToken;
import com.youhome.mobile.utils.JwtTokenUtil;
import com.youhome.service.model.Principal;
import com.youhome.service.service.AuthenticationService;
import com.youhome.service.service.BUserService;
import com.youhome.service.service.JSMSValidateService;
import com.youhome.service.service.SMSService;
import com.youhome.utils.ValidationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

/**
 * Created by chen365 on 2018/09/12.
 */
@Api(tags = "用户")
@RestController
@RequestMapping(value = "/users")
public class UserController {

    @Autowired
    private BUserService bUserService;
    @Autowired
    private AuthenticationService authenticationService;
    //    Spring Security无法注入authenticationManager：No qualifying bean of type AuthenticationManager found for
//    在WebSecurityConfigurerAdapter的实现类当中，重写authenticationManagerBean方法：
//    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
//    @Override
//    public AuthenticationManager authenticationManagerBean() throws Exception {
//        return super.authenticationManagerBean();
//    }
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JSMSValidateService jsmsValidateService;

    @PostMapping(value = "/login")
    @ApiOperation(value = "登陆", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgCode", value = "短信码", paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "msgId", value = "短信ID", paramType = "query")
    })
    public Object login(String phone, String msgCode, String msgId) throws CustomException {

        System.err.println("phone:" + phone);
        if (!ValidationUtils.isPhone(phone)) {
            return new Result(ResultCode.ERROR_PHONE);
        }

        UserDetails userDetails = null;
        try {
            userDetails = authenticationService.loadUserByUsername(phone);
        } catch (UsernameNotFoundException e) {
            e.printStackTrace();
            return new Result(ResultCode.UNREGISTERED_PHONE);
        }

        if (!jsmsValidateService.validate(phone, msgId, msgCode)) {
            return new Result(ResultCode.ERROR_VALIDATE_CODE);
        }

        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();

        //UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(userDetails, msgCode, authorities);
        SMSAuthenticationToken upToken = new SMSAuthenticationToken(userDetails, authorities);
        // Perform the security
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // Reload password post-security so we can generate token
        Principal principal = (Principal) userDetails;
        final String token = new JwtTokenUtil().generateToken(principal);

        return new Result(ResultCode.SUCCESS, token);

        //return null;
    }


}
